/*
  This file is a part of hashutils package.
  (c) 2004 Zeljko Vrba <zvrba@globalnet.hr>

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sfio.h>
#include <cdt.h>
#include <vmalloc.h>
#include <mycrypt.h>
#include "main.h"
#include "cdt_line.h"

static char rcsid[] = "$Id: hdiff.c 2 2007-03-29 14:43:55Z zeljko.vrba $";
const char *Main_argv0;

/******************************************************************************
 * Optimized output of deleted lines.
 *****************************************************************************/

#define SETBIT(v, n) v[(n)>>3] |= 1 << (n&7)
#define ISSET(v, n)  v[(n)>>3] & (1 << (n&7))

/**
   Output interval deletion commands.

   @param	out		Output stream.
   @param	dt		Dictionary holding lines.
   @param	maxn	Maximum deleted line number.
   @param	set		Preallocated array large enough to hold maxn+2 bits.
*/
static void do_optimized_output(
	Sfio_t *out, Dt_t *dt,
	unsigned long maxn, unsigned char *set)
{
	unsigned int start, end;
	Dtlink_t *link;
	
	memset(set, 0, (maxn>>3)+2);

	for(link = dtflatten(dt); link; link = dtlink(dt, link)) {
		unsigned int n = ((struct line*)dtobj(dt, link))->n;
		SETBIT(set, n);
	}

	/* output consecutive intervals */
	for(start = 0; start <= maxn; start++) {
		if(ISSET(set, start)) {
			/* maxn+1'th bit is always 0 so no need for (end < maxn) */
			for(end = start+1; ISSET(set, end); end++)
				;				/* empty body */
			
			if(end-start > 1) sfprintf(out, "%u,%ud\n", start, end-1);
			else sfprintf(out, "%ud\n", start);

			/* continue after string of 1s */
			start = end;
		}
	}
}



/******************************************************************************
 * Implementation of diff algorithm.
 *****************************************************************************/
/* For sed we must escape each \. */
static void print_escaped(Sfio_t *f, const char *str)
{
	/* record separator from sfgetr() is left in str. */
	for(; *str != '\n'; str++) {
		sfputc(f, *str);
		if(*str == '\\') sfputc(f, *str);
	};
	sfputc(f, '\n');
}

/**
   This function makes a set difference and outputs sed commands to stream
   which reconstruct the TO-FILE from the FROM-FILE. The output is in parallel
   with reading FILE2 (no extra storage necessary).
*/
static void diff(Sfio_t *f, Sfio_t *out, Dt_t *old, int halg)
{
	char *record;
	Void_t *obj;
	char hash[256];
	Dtlink_t *link;
	unsigned char *set;
	unsigned long maxn;

	if(Cdt_LineDiscipline.size > 256) {
		sfprintf(sfstderr, "FATAL: hash has more than 256 bytes (2048 bits), exiting.\n");
		exit(1);
	}

	while((record = sfgetr(f, '\n', 0))) {
		unsigned long outlen = Cdt_LineDiscipline.size;
		int err;

		if((err = hash_memory(halg, (unsigned char*)record,
							  sfvalue(f), hash, &outlen)) != CRYPT_OK) {
			sfprintf(sfstderr, "FATAL: crypto error: %s, exiting.\n",
					 error_to_string(err));
			exit(1);
		}

		if((obj = dtmatch(old, hash))) { /* exists in both files */
			dtdelete(old, obj);
		} else {				/* only in second file; output immediately */
			sfprintf(out, "1i\\\n");
			print_escaped(out, record);
		}
	}
	if(sferror(f)) {
		sfprintf(sfstderr, "ERROR reading file: sfgetr: %s\n", strerror(errno));
		exit(1);
	}

	/* find max deleted line number */
	for(link = dtflatten(old); link; link = dtlink(old, link)) {
		struct line *l = dtobj(old, link);
		if(l->n > maxn) maxn = l->n;
	}

	/* output interval deletion commands */
	if((set = vmalloc(LineSet_vmpool, (maxn>>3)+2))) {
		do_optimized_output(out, old, maxn, set);
	} else {
		sfprintf(sfstderr, "WARNING: can't allocate memory for optimized output, writing unoptimized.\n");
		for(link = dtflatten(old); link; link = dtlink(old, link)) {
			struct line *l = dtobj(old, link);
			sfprintf(out, "%ud\n", l->n);
		}
	}
}



/******************************************************************************
 * Implementation of 'main' interface.
 *****************************************************************************/
void Main_usage(const char *message)
{
	sfprintf(sfstderr, "%s\n", message);
	sfprintf(sfstderr, "USAGE: %s [OPTION] HASH FROM-FILE TO-FILE\n", Main_argv0);
	sfprintf(sfstderr, "  -N             don't report duplicates (unordered ONLY)\n");
	sfprintf(sfstderr, "  -o             optimize deleted output at the expense of extra memory\n");
	sfprintf(sfstderr, "\n");
	
	sfprintf(sfstderr, "HASH is one of the following (displayed as HASH/byte length):\n");
	Main_print_hashes();
	exit(1);	
}

int Main_process_option(int argc, char **argv, int *arg)
{
	if(strlen(argv[*arg]) != 2) Main_usage("ERROR: invalid option.");
	switch(argv[*arg][1]) {
	case 'N': LineSet_report_collisions = 0; return 1;
	case 'o': break;
	}
	return 0;
}

void Main_process_files(const char *fname1, const char *fname2, int halg)
{
	Sfio_t *file1, *file2;
	Dt_t *from_set;

	if(!fname2) Main_usage("ERROR: TO-FILE not specified.");

	/* set CDT key size and create Vmlast heap */
	Cdt_LineDiscipline.size = hash_descriptor[halg].hashsize;
	if(!(LineSet_vmpool = vmopen(Vmdcmmap, Vmlast, VM_TRUST))) {
		sfprintf(sfstderr, "FATAL: can't create memory heap, exiting.\n");
		exit(1);
	}

	file1 = Main_file_open(fname1);
	file2 = Main_file_open(fname2);
	if(!(from_set = LineSet_read_file(file1, halg))) {
		sfprintf(sfstderr, "ERROR calculating file hashes, exiting.\n");
		exit(1);
	}
	sfclose(file1);
	file1 = Main_file_open(fname1);
	
	diff(file2, sfstdout, from_set, halg);
}

